#include "common.h"

void printf(const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);

    while (*fmt) {
        if (*fmt == '%') {
            fmt++;  // 跳过%
            switch (*fmt) {
                case '%':   // 处理%%
                    putchar('%');
                    break;
                case 'c':   // 处理字符
                    putchar(va_arg(args, int));
                    break;
                case 's': {  // 处理字符串
                    const char* str = va_arg(args, const char*);
                    while (*str) {
                        putchar(*str++);
                    }
                    break;
                }
                case 'd': {  // 处理整数
                    int num = va_arg(args, int);
                    if (num < 0) { // 处理负数
                        putchar('-');
                        num = -num;
                    }
                    char buffer[20];    // 足够存储一个32位整数
                    int i = 0;          // 索引
                    do {
                        buffer[i++] = num % 10 + '0';
                        num /= 10;
                    } while (num > 0);  // 转换为字符串
                    while (i > 0) {
                        putchar(buffer[--i]);
                    }
                    break;
                }
                case 'x': {  // 处理十六进制    
                    uint32_t num = va_arg(args, uint32_t);
                    char hexDigits[] = "0123456789ABCDEF";
                    char buffer[20];
                    int i = 0;
                    do {
                        buffer[i++] = hexDigits[num % 16];
                        num /= 16;
                    } while (num > 0);
                    while (i > 0) {
                        putchar(buffer[--i]);
                    }
                    break;
                }
                default:
                    putchar('%');   // 未知格式符，输出%
                    putchar(*fmt);
                    break;
            }
        }
        else {
            putchar(*fmt);
        }
        fmt++;
    }
    va_end(args);
}

void* memset(void* dest, char c, size_t len) {
    char* p = (char*)dest;
    while (len--) {
        *p++ = c;
    }
    return dest;
}

void* memcpy(void* dest, const void* src, size_t len) {
    char* d = (char*)dest;
    char* s = (char*)src;
    while (len--) {
        *d++ = *s++;
    }
    return dest;
}

char* strcpy(char* dest, const char* src) {
    char* d = dest;
    while ((*d++ = *src++) != '\0');
    return dest;
}

int strcmp(const char* s1, const char* s2) {
    while (*s1 == *s2) {
        s1++;
        s2++;
    }
    return *(unsigned char*)s1 - *(unsigned char*)s2;
}
